import React from 'react';
import {  Toast } from 'antd-mobile';
import axios from 'axios';
import { getLocalCity } from '../../utils/localCity';
import { List, AutoSizer } from 'react-virtualized';
import './index.scss';
import TitleHeader from '../../components/TitleHeader'

export default class Citylist extends React.Component {
  state = {
    cityList: {},
    cityIndex: [],
    active: 0
  }

  firstCity = ['北京', '上海', '广州', '深圳']

  listRef = React.createRef()

  componentDidMount() {
    this.getCityList()
  }

  handleAreaData = list => {
    const cityList = {}

    list.forEach(item => {
      let firstVal = item.short.substr(0, 1)

      if (cityList[firstVal]) {
        cityList[firstVal].push(item)
      } else {
        cityList[firstVal] = [item]
      }
    })

    const cityIndex = Object.keys(cityList).sort()

    return {
      cityIndex,
      cityList
    }
  }

  getCityList = async () => {
    const { data: areaData } = await axios.get('http://127.0.0.1:8080/area/city?level=1')

    if (areaData.status !== 200) {
      return alert(areaData.description)
    }

    const { cityIndex, cityList } = this.handleAreaData(areaData.body)

    const { data: hotData } = await axios.get('http://127.0.0.1:8080/area/hot')

    if (hotData.status !== 200) {
      return alert(hotData.description)
    }

    cityList['hot'] = hotData.body
    cityIndex.unshift('hot')

    const localData = await getLocalCity()

    cityList['#'] = [localData]
    cityIndex.unshift('#')

    this.setState({
      cityList,
      cityIndex
    })
  }

  renderHeader = () => {
    return (
      <TitleHeader title="城市列表" />
    )
  }

  handleTitle = (title) => {
    return title === 'hot' ? '热门城市' : title.toUpperCase()
  }

  changeCity = (res) => {
    if(!this.firstCity.includes(res.label)) {
      return Toast.info('当前城市暂未开放', 100)
    }

    localStorage.setItem('local_city', JSON.stringify(res))
    this.props.history.push('/')

  }

  rowRenderer = ({
    key, // Unique key within array of rows
    index, // Index of row within collection
    isScrolling, // The List is currently being scrolled
    isVisible, // This row is visible within the List (eg it is not an overscanned row)
    style, // Style object to be applied to row (to position it)
  }) => {
    const { cityIndex, cityList } = this.state

    const title = cityIndex[index]
    const arr = cityList[title]

    return (
      <div key={key} style={style}>
        <div className="flagTitle">{this.handleTitle(title)}</div>
        {arr.map(item => {
          return <div key={item.value} className="cityLabel" onClick={() => this.changeCity(item)}>{item.label}</div>
        })}
      </div>
    );
  }

  rowHeight = ({ index }) => {
    const { cityIndex, cityList } = this.state

    return cityList[cityIndex[index]].length * 45 + 45
  }

  onRowsRendered = ({ startIndex }) => {
    const { active } = this.state
    console.log(active, startIndex)
    if (startIndex === active) {
      return
    }

    this.setState({
      active: startIndex
    })
  }

  renderList = () => {
    return (
      <AutoSizer>
        {({ height, width }) => (
          <List
            width={width}
            height={height}
            rowCount={this.state.cityIndex.length}
            rowHeight={this.rowHeight}
            rowRenderer={this.rowRenderer}
            onRowsRendered={this.onRowsRendered}
            measureAllRows={true}
            scrollToAlignment='start'
            ref={this.listRef}
          />
        )}
      </AutoSizer>
    )
  }

  renderSidebar = () => {
    return (
      <div className="slidbarBox">
        {this.state.cityIndex.map((item, index) => {
          return <div key={item} onClick={() => {
            console.log(index)
            this.listRef.current.scrollToRow(index)
          }   }>
            <span className={index === this.state.active ? 'active' : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
          </div>
        })}
      </div>
    )
  }

  render() {
    return (
      <div className="cityBox">
        {this.renderHeader()}

        {this.renderList()}

        {this.renderSidebar()}
      </div>
    )
  }
}